<?php
// +----------------------------------------------------------------------
// | 知识星球[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2019 abcblockchain.io
// +----------------------------------------------------------------------
// | 后台管理使用了HisiPHP
// +----------------------------------------------------------------------
// | Author: abcblockchain.io
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;
use think\Db;
use app\common\util\Bitcoin;
use think\config;

/**
 * 用户币种模型
 * @package app\common\model
 */
class UsersCurrency extends Model
{
    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;


    /**
     * 创建用户币种关系
     * @param array $data
     * @author abcblockchain.io
     * @return stirng|array
     */
    public function createUsersCurrency($userId, $currencyId)
    {
        $map = [];
        $map['user_id'] = $userId;
        $map['currency_id'] = $currencyId;
        $isHave = $this->where($map)->find();
        if($isHave){
            return true;
            exit;
        }
        $map['num'] = 0;
        $map['forzen_num'] = 0;

        $res = $this->insertGetId($map);
        if (!$res) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取用户资金列表
     * @author
     * @param $userId
     * @return array|false|\PDOStatement|string|\think\Collection
     */
    public function getUserCurrencyList($userId, $type=0, $startNo = 0, $limit = 10)
    {
        $vnsPrice = $this->getVnsPrice();
        $map['uc.user_id'] = $userId;
        $map['uc.status'] = 1;
        $map['c.contract_address'] = array('neq','');
        if($type > 0){
            $map['uc.num'] = array('gt',0);
        }
        $startNo = $startNo * $limit;
        $currencyList = $this->alias('uc')->join('currency c', 'uc.currency_id=c.id')->where($map)->field('c.id,uc.num,uc.recharge_url,c.currency_name,c.currency_mark,c.logo,last_price')->limit($startNo, $limit)->select();
        if($currencyList){
            foreach ($currencyList as $k => $v) {
                if($v['id'] == 1){
                    $currencyList[$k]['price'] = sprintf("%.4f",$v['num']);
                }elseif($v['id'] == 2){
                    $currencyList[$k]['price'] = sprintf("%.4f",$v['num'] * $vnsPrice);
                }else{
                    $currencyList[$k]['price'] = sprintf("%.4f",$v['num'] * $v['last_price'] * $vnsPrice);
                }
            }
        }
        return $currencyList ? $currencyList : [];
    }

    /**
     * 获取账户总额
     * @author
     * @param $userId
     * @return int|string
     */
    public function getUserCurrencySum($userId){
        $vnsPrice = $this->getVnsPrice();
        $map['uc.user_id'] = $userId;
        $map['uc.status'] = 1;
        $currencyList = $this->alias('uc')->join('currency c', 'uc.currency_id=c.id')->where($map)->field('c.id,uc.num,last_price')->select();
        $currencyPriceSum = 0;
        if($currencyList){
            foreach ($currencyList as $k => $v) {
                if($v['id'] == 1){
                    $currencyPriceSum = $currencyPriceSum + $v['num'];
                    //$currencyList[$k]['price'] = sprintf("%.4f",$v['num']);
                }elseif($v['id'] == 2){
                    $currencyPriceSum = $currencyPriceSum + ($v['num'] * $vnsPrice);
                    //$currencyList[$k]['price'] = sprintf("%.4f",$v['num'] * $vnsPrice);
                }else{
                    $currencyPriceSum = $currencyPriceSum + ($v['num'] * $v['last_price'] * $vnsPrice);
                    //$currencyList[$k]['price'] = sprintf("%.4f",$v['num'] * $v['last_price'] * $vnsPrice);
                }
            }
        }
        if($currencyPriceSum > 0){
            $currencyPriceSum = sprintf("%.4f",$currencyPriceSum);
        }
        return $currencyPriceSum;
    }

    /**
     * 获取vnsPrice
     * @author
     * @return int
     * @throws \Exception
     */
    public function getVnsPrice(){
        /*$url = 'https://api.coinx.pro/rest/v1/ticker';
        $params['symbol'] = 'VNS/USDT';
        $data = http($url, $params);*/
        $data = Db::name('currency')->where('id', 2)->field('last_price')->find();
        if ($data) {
            //$data = json_decode($data, true);
            if($data['last_price']){
                return $data['last_price'];
            }else{
                return 0;
            }
        } else {
            return 0;
        }
    }

    /**
     * 获取用户token余额
     * @author
     * @param $userId
     * @param $currencyId
     * @return mixed
     */
    public function getUserTokenNum($userId, $currencyId)
    {
        $map = [];
        $map['user_id'] = $userId;
        $map['currency_id'] = $currencyId;
        $numInfo = $this->where($map)->field('num')->find();
        return $numInfo['num'];
    }

    /**
     * 账户资产变动
     * @author
     * @param $num
     * @param $numType
     * @param $currencyId
     * @param $userId
     * @return int|true
     */
    public function changeUserNum($num, $numType, $currencyId, $userId)
    {
        $map = [];
        $map['user_id'] = $userId;
        $map['currency_id'] = $currencyId;
        if ($numType == 1) {
            $res = $this->where($map)->setInc('num', $num);
        } elseif ($numType == 2) {
            $res = $this->where($map)->setDec('num', $num);
        }
        return $res;
    }

    /**
     * 获取用户钱包地址
     * @author
     * @param $currencyId
     * @param $userId
     * @return bool|mixed|string
     */
    public function getUserCurrencyAddress($currencyId, $userId)
    {
        $map['user_id'] = $userId;
        $map['currency_id'] = $currencyId;
        $userCurrencyInfo = $this->where($map)->field('recharge_url')->find();
        if ($userCurrencyInfo['recharge_url']) {
            return $userCurrencyInfo['recharge_url'];
        } else {
            $address = '';
            if ($currencyId == 1) {
                $bitcoin = new Bitcoin(Config::get('queue.btc_user'), Config::get('queue.btc_pwd'));
                $address = $bitcoin->getnewaddress($userId);
            } elseif ($currencyId == 2) {
                vendor("ethereum.ethereum");
                $eth = new \Ethereum(Config::get('queue.rpc_ip'), Config::get('queue.rpc_port'));
                $address = $eth->personal_newAccount(Config::get('queue.rpc_pwd'));
            }
            if ($address) {
                $upData['recharge_url'] = $address;
                $res = $this->where($map)->update($upData);
                if ($res) {
                    return $address;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        }

    }

    /**
     * 获取用户币种信息
     * @author
     * @param $currencyId
     * @param $userId
     * @return array|false|\PDOStatement|string|Model
     */
    public function getUserCurrencyInfo($currencyId, $userId)
    {
        $map['user_id'] = $userId;
        $map['currency_id'] = $currencyId;
        $userCurrencyInfo = $this->where($map)->field('num,from_block')->find();
        return $userCurrencyInfo ? $userCurrencyInfo : [];
    }

}